<template>
    <div>
        <div class="file-list">
            <div class="van-demo-upload-list" v-for="(item, index) in defaultFileList" @click="handleOperate(item)">
                <img class="other" v-if="checkPreType(['jpg', 'jpeg', 'png', 'gif'],item)" :src="item.previewUrl || item.url">
                <video class="other" v-else-if="checkPreType(videoFormat,item)" :src="item.url"></video>
                <img class="other" v-else-if="checkPreType(['pdf'],item)" src="../../assets/images/pdf.png">
                <img class="other" v-else-if="checkPreType(['doc','docx'],item)" src="../../assets/images/word.png">
                <img class="other" v-else-if="checkPreType(['xlsx'],item)" src="../../assets/images/ecel.png">
                <img class="other" v-else-if="checkPreType(['pptx','ppt'],item)" src="../../assets/images/ppt.png">
                <img class="other" v-else-if="checkPreType(['apk','APK'],item)" src="../../assets/images/apk.png">
                <img class="other" v-else-if="checkPreType(['txt'],item)" src="../../assets/images/txt.png">
                <img class="other" v-else src="../../assets/images/otherFile.png">
                <span class="word">{{item.fileName}}</span>
                <div class="demo-upload-list-cover" v-if="!readOnly">
                    <van-icon name="cross" @click.native="handleDelete(item, index, $event)" />
                </div>
            </div>
        </div>
        <div class="file-list" v-if="!readOnly">
            <div class="van-demo-upload-list" v-for="(item, index) in fileList" @click="handleOperate(item)">
                <img class="other" v-if="checkPreType(['jpg', 'jpeg', 'png', 'gif'],item)" :src="item.previewUrl || item.url">
                <video class="other" v-else-if="checkPreType(videoFormat,item)" :src="item.url"></video>
                <img class="other" v-else-if="checkPreType(['pdf'],item)" src="../../assets/images/pdf.png">
                <img class="other" v-else-if="checkPreType(['doc','docx'],item)" src="../../assets/images/word.png">
                <img class="other" v-else-if="checkPreType(['xlsx'],item)" src="../../assets/images/ecel.png">
                <img class="other" v-else-if="checkPreType(['pptx','ppt'],item)" src="../../assets/images/ppt.png">
                <img class="other" v-else-if="checkPreType(['apk','APK'],item)" src="../../assets/images/apk.png">
                <img class="other" v-else-if="checkPreType(['txt'],item)" src="../../assets/images/txt.png">
                <img class="other" v-else src="../../assets/images/otherFile.png">
                <span class="word">{{item.fileName}}</span>
                <div class="demo-upload-list-cover">
                    <van-icon name="cross" @click.native="handlePreDelete(index, $event)" />
                </div>
            </div>
            <div class="list-icon" v-if="fileNumber < this.maxNumber" @click="handleUpload">
                <img src="../../assets/images/upload.png">
            </div>
        </div>
        <!-- 视频预览 -->
        <van-overlay :show="showOverlay">
            <div class="wrapper">
                <van-icon name="clear" @click="showOverlay = false" />
                <video v-if="showOverlay" controls autoplay name="media">
                    <source :src="videoUrl">
                </video>
            </div>
        </van-overlay>
    </div>
</template>

<script>
    import { uploadAttach, queryFileInfo } from '@/api/common';
    import { ImagePreview } from 'vant';
    import Setting from '../../setting';

    export default {
        props: {
            defaultFiles: {
                type: Array,
                default: () => {
                    return []
                }
            },
            accept: {
                type: String,
                default: '.png,.jpg,.jpeg,.doc,.docx,.xls,.xlsx,.pdf,.ppt,.pptx,.web,.txt,.mp4'
            },
            // 文件最大：50M
            maxSize: {
                type: Number,
                default: 51200
            },
            // 视频支持的格式
            videoFormat: {
                type: Array,
                default: () => {
                    return ['mp4']
                }
            },
            // 只读模式
            readOnly: {
                type: Boolean,
                default: false
            },
            // 限制文件个数
            maxNumber: {
                type: Number,
                default: 5
            },
        },
        computed: {
            defaultFileList: {
                get () {
                    return this.defaultFiles;
                },
                set () { }
            },
            fileNumber () {
                return this.defaultFileList.length + this.fileList.length
            }
        },
        data () {
            return {
                showOverlay: false,
                videoUrl: '',
                delFileIds: [],
                fileList: []
            }
        },
        methods: {
            // 上传附件
            handleUpload () {
                if (this.fileNumber >= this.maxNumber) {
                    this.$Notify({ type: "warning", message: `文件个数不能超过${this.maxNumber}个!` });
                    return false;
                }
                let _this = this;
                wx.chooseImage({
                    count: 1, // 默认9
                    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
                    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
                    quality: 0.5, //压缩质量，范围0～1，数值越小，质量越低，压缩率越高（仅对jpg有效）
                    success: function (res) {
                        var localIds = res.localIds[0]; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
                        let fileName = localIds.slice(localIds.lastIndexOf("/") + 1);
                        let type = fileName.slice(fileName.lastIndexOf(".") + 1);
                        wx.getLocalImgData({
                            localId: localIds,
                            success: function (source) {
                                if (source.localData) {
                                    _this.getFileFrombase64(source.localData, fileName, type);
                                }
                            }
                        });
                    }
                });
            },
            // 将base64转为file对象
            getFileFrombase64 (data, fileName, type) {
                const dataArr = data.split(",");
                const byteString = atob(dataArr[1]);
                const options = {
                    type: "image/" + (type == 'jpg' ? 'jpeg' : type),
                    endings: "native"
                }
                const u8Arr = new Uint8Array(byteString.length);
                for (let i = 0; i < byteString.length; i++) {
                    u8Arr[i] = byteString.charCodeAt(i);
                }
                let fileOfBlob = new File([u8Arr], fileName, options);
                uploadAttach(fileOfBlob).then(res => {
                    if (res.code === 1000 && res.data) {
                        if (Setting.codeMode === "uapRelease") {
                            res.data.url = this.changeUrlPre(res.data.url);
                            res.data.previewUrl = this.changeUrlPre(res.data.previewUrl);
                        }
                        this.fileList.push(res.data);
                        this.sendValue();
                    }
                })
            },
            // uap环境附件预览地址前缀替换
            changeUrlPre (url) {
                if (!url) return url;
                let str = url.split("/").slice(0, 3).join("/");
                let newPre = Setting.fileUrlPre + sessionStorage.getItem("UAP_ISC_PORT");
                return url.replace(str, newPre);
            },
            // 附件预览及下载
            handleOperate (item) {
                let ts = item.url.split("ts=")[1];
                if ((new Date().getTime() - (ts * 1000)) / 6000 >= 30) {
                    queryFileInfo({ fileCode: item.fileCode }).then(res => {
                        if (res.code === 1000 && res.data) {
                            if (this.checkPreType(['jpg', 'jpeg', 'png', 'gif'], item)) { // 图片
                                ImagePreview({
                                    images: [res.data.url],
                                    closeable: true,
                                });
                            } else if (this.checkPreType(this.videoFormat, item)) { // 视频
                                this.showOverlay = true;
                                this.videoUrl = res.data.url;
                            } else { // 不支持预览，点击下载
                                window.open(res.data.url, '_blank');
                            }
                        }
                    })
                } else {
                    if (this.checkPreType(['jpg', 'jpeg', 'png', 'gif'], item)) { // 图片
                        ImagePreview({
                            images: [item.url],
                            closeable: true,
                        });
                    } else if (this.checkPreType(this.videoFormat, item)) { // 视频
                        this.showOverlay = true;
                        this.videoUrl = item.url;
                    } else { // 不支持预览，点击下载
                        window.open(item.url, '_blank');
                    }
                }
            },
            // 删除默认附件
            handleDelete (item, index, e) {
                e.stopPropagation(); // 阻止冒泡
                this.defaultFileList.splice(index, 1);
                this.delFileIds.push(item.fileCode);
                this.$emit('removeFiles', this.delFileIds);
                this.sendValue();
            },
            // 删除未保存的附件
            handlePreDelete (index, e) {
                e.stopPropagation(); // 阻止冒泡
                this.fileList.splice(index, 1);
                this.sendValue();
            },
            // 验证附件类型
            checkPreType: function (arr, item) {
                var type = '';
                if (item.fileName.lastIndexOf('.') !== -1) {
                    type = item.fileName.slice(item.fileName.lastIndexOf('.') + 1).toLowerCase();
                }
                var flag = false;
                arr.filter(val => {
                    if (val === type) {
                        flag = true;
                    }
                })
                return flag;
            },
            // 传递值
            sendValue () {
                let arr = [...this.defaultFiles, ...this.fileList];
                // 当前所有附件
                this.$emit('uploadFiles', arr);
                this.$emit('uploadFileIds', this.extractFileId(arr));
                // 此次新增的附件
                this.$emit('uploadCurFiles', this.fileList);
                this.$emit('uploadCurFileIds', this.extractFileId(this.fileList));
            },
            extractFileId (arr) {
                let data = [];
                arr.forEach(item => {
                    data.push(item.fileCode);
                })
                return data;
            },
            // 重置
            reset () {
                this.videoUrl = '';
                this.delFileIds = [];
                this.fileList = [];
                this.defaultFileList = [];
            }
        }
    }
</script>

<style scoped lang="less">
    .file-list {
        width: 100%;
        box-sizing: border-box;
        .van-demo-upload-list {
            display: inline-block;
            width: 80px;
            height: 80px;
            text-align: center;
            line-height: 80px;
            border: 1px solid transparent;
            border-radius: 4px;
            overflow: hidden;
            background: #fff;
            position: relative;
            box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
            margin-right: 6px;
            margin-bottom: 6px;
            img {
                width: 100%;
                height: 100%;
            }
            .other {
                width: 85%;
                height: 70%;
            }
            .demo-upload-list-cover {
                position: absolute;
                top: -8px;
                right: -8px;
                background: rgba(0, 0, 0, 0.6);
                width: 25px;
                height: 25px;
                border-radius: 40%;
                z-index: 99;
                i {
                    position: absolute;
                    color: #fff;
                    font-size: 10px;
                    z-index: 9;
                    top: 10px;
                    left: 3px;
                }
            }
            span.word {
                font-size: 13px;
                position: absolute;
                width: 100%;
                bottom: 0;
                height: 16px;
                line-height: 16px;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
                left: 0;
            }
        }
        .list-icon {
            width: 80px;
            height: 80px;
            cursor: pointer;
            background-size: 100% 100%;
            border: 1px solid rgb(244, 244, 244);
            img {
                width: 75%;
                height: 75%;
                display: block;
                margin: 15% auto;
            }
        }
    }
    .van-overlay {
        z-index: 200;
    }
    .wrapper {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 100%;
        .van-icon {
            position: absolute;
            top: 15px;
            right: 18px;
            font-size: 23px;
            color: #c8c9cc;
        }
        video {
            width: 100%;
            max-height: 50%;
        }
    }
</style>
